package com.pingan.glue.gluegame.service.impl;

import com.pingan.glue.gluegame.common.ErrorMessage;
import com.pingan.glue.gluegame.common.FaceExcelDto;
import com.pingan.glue.gluegame.exception.BusinessException;
import com.pingan.glue.gluegame.service.ExcelService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;


@Service
public class ExcelServiceImpl implements ExcelService {

    private final static Logger LOGGER = LoggerFactory.getLogger(ExcelServiceImpl.class);

    @Override
    public List<FaceExcelDto> analysisExcel(String fileName) {
        LOGGER.info("ExcelServiceImpl_analysisExcel_fileName:{}",fileName);
        if(!validateExcel(fileName)){
            throw new BusinessException(ErrorMessage.EXCEL_NAME_ERROR);
        }
        InputStream is = null;
        try{
            is = new FileInputStream(fileName);
            Workbook wb = workbookFromIs(fileName, is);
            List<FaceExcelDto> faces =  readExcel(wb);
            return faces;
        }catch(Exception e){
            LOGGER.info("ExcelServiceImpl_analysisExcel_error:",e);
        } finally{
            if(is !=null){
                try{
                    is.close();
                }catch(IOException e){
                    is = null;
                }
            }
        }
        return null;
    }

    private List<FaceExcelDto> readExcel(Workbook workbook){
        Sheet sheet = workbook.getSheetAt(0);
        int lastRowNum = sheet.getLastRowNum();
        List<FaceExcelDto> faces = new ArrayList<>();
        for (int i=1;i<=lastRowNum;i++){
            FaceExcelDto dto = new FaceExcelDto();
            Row row = sheet.getRow(i);
            int lastCellnum = row.getLastCellNum();
            if (lastCellnum != 8){
                return null;
            }
            dto.setName(row.getCell(0)==null?null:row.getCell(0).getStringCellValue());
            row.getCell(1).setCellType(1);
            dto.setMobile(row.getCell(1).getStringCellValue());
            dto.setUsername(row.getCell(2).getStringCellValue());
            dto.setPath(row.getCell(3).getStringCellValue());
            dto.setOccupation(row.getCell(4).getStringCellValue());
            dto.setBloodType(row.getCell(5).getStringCellValue());
            dto.setConstellation(row.getCell(6).getStringCellValue());
            faces.add(dto);
        }
        return faces;
    }


    private Workbook workbookFromIs(String fileName, InputStream is) throws IOException {
        Workbook wb;
        if(isExcel2003(fileName)){
            wb = new HSSFWorkbook(is);
        }else{
            wb = new XSSFWorkbook(is);
        }
        return wb;
    }

    /**
     * 验证EXCEL文件
     * @param filePath
     * @return
     */
    public boolean validateExcel(String filePath){
        if (filePath == null || !(isExcel2003(filePath) || isExcel2007(filePath))){
            return false;
        }
        return true;
    }
    private boolean isExcel2003(String filePath) {
        return filePath.matches("^.+\\.(?i)(xls)$");
    }


    private boolean isExcel2007(String filePath) {
        return filePath.matches("^.+\\.(?i)(xlsx)$");
    }
}
